import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        System.out.println(new Solution1().subsets(new int[]{1,2,3}));
    }
}

//回溯
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        backtracking(nums, 0, new ArrayDeque<>(), ans);;
        return ans;
    }

    void backtracking(int[] nums, int i, Deque<Integer> cur, List<List<Integer>> ans) {
        if (nums.length == i) {
            ans.add(new ArrayList<>(cur));
            return;
        }

        //不取nums[i]
        backtracking(nums, i + 1, cur, ans);

        //取nums[i]
        cur.addLast(nums[i]);
        backtracking(nums, i + 1, cur, ans);
        cur.removeLast();
    }
}

//使用二进制mask
class Solution1 {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        int mask = 0;
        while (mask < 1 << nums.length) {
            ans.add(makeMaskedSubset(nums, mask));
            mask++;
        }
        return ans;
    }

    private List<Integer> makeMaskedSubset(int[] nums, int mask) {
        List<Integer> subset = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if ((mask >> i & 1) == 1) {
                subset.add(nums[i]);
            }
        }
        return subset;
    }
}
